package com.example.equipment.bean.config;

import com.example.equipment.annotation.IgnoreCheck;
import com.example.equipment.bean.enums.ResultEnum;
import com.example.equipment.bean.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

@Aspect
@Component
public class UserAspect {

    @Pointcut("execution(* com.example.equipment.controller..*.*(..))")//切入面在controller包下的所有方法
    public void match() {
    }

    @Around("match()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        Object result = null;
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();//获取当前请求
        HttpSession session = attr.getRequest().getSession(true);
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method targetMethod = methodSignature.getMethod();

        boolean isLogin = isLogin(session);


        if (!isLogin && targetMethod.getAnnotation(IgnoreCheck.class) == null) {
            //未登录
            return new OpenApiResult(ResultEnum.SESSION_TIMEOUT);
        } else {
            result = pjp.proceed(pjp.getArgs());//执行后面的业务代码
            return result;
        }

    }

    public boolean isLogin(HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser != null) {
            return true;
        }
        return false;
    }
}
